﻿using Microsoft.EntityFrameworkCore;
using Reporting.Infrastructure;
using System.Reflection;
using Consul;
using Autofac;
using Reporting.API.Filter;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using Newtonsoft.Json.Serialization;

namespace Reporting.API.Extensions
{
    /// <summary>
    /// 服务集合扩展
    /// </summary>
    public static class ServiceCollectionExtensions
    {
        /// <summary>
        /// 注册JWT身份验证服务
        /// </summary>
        /// <param name="collection">服务集合</param>
        /// <param name="configuration">配置对象</param>
        public static void AddJwt(this IServiceCollection collection, IConfiguration configuration)
        {
            // 注册JWT Bearer身份验证
            collection.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>
                {
                    // 取出配置文件中的私钥，并进行UTF8编码
                    var secretByte = Encoding.UTF8.GetBytes(configuration["Authentication:SecretKey"]);
                    options.TokenValidationParameters = new TokenValidationParameters()
                    {
                        // 验证JWT的发布者是否有效
                        ValidateIssuer = true,
                        ValidIssuer = configuration["Authentication:Issuer"],

                        // 验证JWT的接收者是否有效
                        ValidateAudience = true,
                        ValidAudience = configuration["Authentication:Audience"],

                        // 验证JWT是否过期
                        ValidateLifetime = true,

                        // 设置验证JWT签名的私钥
                        IssuerSigningKey = new SymmetricSecurityKey(secretByte)
                    };
                });
        }

        public static IServiceCollection AddServices(this IServiceCollection services, IConfiguration configuration, WebApplicationBuilder hostBuilder)
        {
            services.AddDbContext<ReportingDbContext>(options =>options.UseMySql(configuration.GetConnectionString("DefaultConnection"),
                new MySqlServerVersion(new Version(5, 7, 0)))); // 使用 MySQL 5.7

            // 注入中介者
            services.AddMediatR(cfg => cfg.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly()));

            // 注入 AutoMapper
            services.AddAutoMapper(typeof(MapingProfile));

            // 注册仓储
            services.AddScoped(typeof(IBaseRepository<>), typeof(BaseRepository<>));

            // 注入 Consul 客户端
            var consulAddress = configuration["Consul:Address"];
            services.AddSingleton<IConsulClient>(new ConsulClient(consulConfig =>
            {
                consulConfig.Address = new Uri(consulAddress);
            }));

            // 注入七牛云工具类
            services.AddScoped<QiniuUtils>();

            // 注册Autofac模块
            hostBuilder.Host.ConfigureContainer<ContainerBuilder>(containerBuilder =>
            {
                containerBuilder.RegisterModule(new AutofaModuleRegister());
            });

            //注入全局异常处理 
            services.AddControllers(x => x.Filters.Add<GlobalExceptionFilter>());


            services.AddControllers().AddNewtonsoftJson(options =>
            {
                options.SerializerSettings.ContractResolver = new DefaultContractResolver();
            });
            return services;
        }
    }
}